package com.zhangzhan.job;

import com.zhangzhan.domain.commcon.App;
import com.zhangzhan.domain.entity.Article;
import com.zhangzhan.service.ArticleService;
import com.zhangzhan.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 博客文章定时从redis中更新浏览量
 * @date 2022/12/4 21:41
 */
@Component
@Slf4j
public class ArticleJob {

    @Autowired
    RedisCache redisCache;

    @Autowired
    ArticleService articleService;

    @Scheduled(cron = "0/59 * * * * ?")
    public void articleScheduledJob(){
        //获取redis中的hash数据
        Map<String, Integer> cacheMap = redisCache.getCacheMap(App.ARTICLE_VIEWCOUNT);
        //需要批量存入
        //map转成ArticleList
        Set<Map.Entry<String, Integer>> entries = cacheMap.entrySet();
        List<Article> articleList = entries.stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue())).collect(Collectors.toList());
        //更改数据库中的数据
        try {
            articleService.updateBatchById(articleList);
        } catch (Exception e) {
            log.error("博客文章浏览量数据更新失败：{}" , e);
        }
        log.info("博客文章浏览量数据更新成功");
    }
}
